<?php
/*
剑指 Offer 32 - III. 从上到下打印二叉树 III
请实现一个函数按照之字形顺序打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右到左的顺序打印，第三行再按照从左到右的顺序打印，其他行以此类推。



例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果：

[
  [3],
  [20,9],
  [15,7]
]


提示：

节点总数 <= 1000



难度：中等

https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/


*/

require_once '../class/TreeNode.class.php';
$arr1 = [3,9,20,null,null,15,7];
$head1 = generateTreeByArray($arr1);
$obj = new Code_Offer32_3();
$res = $obj->main($head1);
var_dump($res);

class Code_Offer32_3
{
    public function main($root)
    {
        if (!$root) {
            return [];
        }
        $res = [];
        $queue = new SplQueue();
        $queue->enqueue($root);
        $bIsOdd = false;
        while (!$queue->isEmpty()) {
            $size = $queue->count();
            $tmp = [];
            for ($i = 0; $i < $size; $i++) {
                $cur = $queue->dequeue();
                $tmp[] = $cur->val;
                $cur->left != null && $queue->enqueue($cur->left);
                $cur->right != null && $queue->enqueue($cur->right);
            }
            if ($bIsOdd) {
                $tmp = array_reverse($tmp);
            }
            $res[] = $tmp;
            $bIsOdd = !$bIsOdd;
        }
        return $res;
    }
}